<template>
  <div id="bottomLeft">
    <div class="bg-color-black">
      <!-- 头部 -->
      <div class="d-flex pt-2 pl-2">
        <span>
          <icon name="chart-bar" class="text-icon" />
        </span>
        <div class="d-flex">
          <span class="fs-xl text mx-2">图片上传预览</span>
        </div>
      </div>

      <!-- 上传/预览区 -->
      <div class="upload-container" @click="triggerUpload">
        <!-- 隐藏的文件输入框 -->
        <input ref="fileInput" type="file" accept="image/*" @change="onFileChange" style="display: none;" />
        <!-- 预览图 -->
        <img v-if="imageUrl" :src="imageUrl" class="image-preview" alt="预览图片" />
        <!-- 占位提示 -->
        <div v-else class="upload-placeholder">
          点击上传图片
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import imageFile from "@/assets/image/1.png"
export default {
  name: 'BottomLeftUploader',
  data() {
    return {
      imageUrl: imageFile
    };
  },
  methods: {
    triggerUpload() {
      this.$refs.fileInput.click();
    },
    onFileChange(event) {
      const file = event.target.files[0];
      if (!file) return;
      if (!file.type.startsWith('image/')) {
        return alert('只能上传图片！');
      }
      // console.log(file);
      // 释放旧 URL
      if (this.imageUrl) {
        URL.revokeObjectURL(this.imageUrl);
        
        
        
      }
      // 创建新 URL 并预览
      this.imageUrl = URL.createObjectURL(file);
      this.$emit('image-uploaded', this.imageUrl); 
      // **关键：清空 input，让下一次选同一文件也会触发 change**
      event.target.value = '';
    }
  },
  beforeDestroy() {
    if (this.imageUrl) {
      URL.revokeObjectURL(this.imageUrl);
    }
  }
};
</script>

<style lang="scss" scoped>
$box-height: 520px;
$box-width: 100%;

#bottomLeft {
  padding: 20px 16px;
  height: $box-height;
  width: $box-width;
  border-radius: 5px;

  .bg-color-black {
    position: relative;
    height: $box-height - 35px;
    border-radius: 10px;
    background-color: #000;
    overflow: hidden;

    .text {
      color: #c3cbde;
    }

    .upload-container {
      width: 100%;
      height: 100%;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .upload-placeholder {
      color: #666;
      font-size: 16px;
      user-select: none;
    }

    .image-preview {
      width: 100%;
      height: 100%;
      object-fit: cover;
      display: block;
    }
  }
}
</style>
